﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace Unimaq.FacturaDBS_Spring.Util
{
    public class ContextoDBSpring : IDisposable
    {
        private SqlConnection conexion;
        private SqlTransaction tx;

        public static ContextoDBSpring GetContexto()
        {
            ContextoDBSpring ctx = new ContextoDBSpring();
            ctx.Load();
            return ctx;
        }

        public SqlTransaction GetTx()
        {
            return tx;
        }

        public void Load()
        {
            string datosConexion = System.Configuration.ConfigurationManager.ConnectionStrings["SpringVersion11"].ConnectionString;
            conexion = new SqlConnection(datosConexion);
            conexion.Open();
        }

        public void Cerrar()
        {
            conexion.Close();
        }

        public SqlConnection GetConexion()
        {
            return conexion;
        }

        public void LoadTransaction()
        {
            tx = conexion.BeginTransaction();
        }

        public void ConfirmarTx()
        {
            tx.Commit();
            tx = null;
        }

        public void RechazarTx()
        {
            tx.Rollback();
            tx = null;
        }

        public void Dispose()
        {
            if (tx != null)
            {
                tx.Rollback();
            }

            this.Cerrar();
        }
    }
}
